<template>
  <div class="about">
    <el-form :inline="true" :model="queryInfo" class="demo-form-inline">
    </el-form>
    <div class="mb20">
      <el-button @click="toAdd" type="primary" icon="Plus" plain>新增</el-button>
    </div>
    <el-scrollbar max-height="500px">
      <el-table :data="kcArray" style="width: 100%" empty-text="没有数据">
        <el-table-column type="selection" width="55" />
        <el-table-column fixed prop="id" label="id" width="80" />
        <el-table-column prop="courseName" label="课程名" width="120" />
        <el-table-column prop="courseTime" label="时长" width="120" />
        <el-table-column prop="courseMount" label="课件数量" width="120" />
        <el-table-column prop="tabularChart" label="图像" width="120" >
          <template #default="scope">
            <el-image v-if="scope.row.tabularChart" style="width: 100px; height: 100px" :src="url+scope.row.tabularChart" :fit="fit" />
          </template>
        </el-table-column>
        <el-table-column prop="courseVideo" label="视频" width="120" >
        </el-table-column>
        <el-table-column prop="courseIntroduce"       label="简介" width="120" />
        <el-table-column prop="applicablePopulation"  label="适用人群" width="120" />
        <el-table-column prop="teacherName"           label="分类" width="120" />
        <el-table-column prop="learnHarvest"          label="学习收获" width="120" />
        <el-table-column prop="subscriptionNotice"    label="订阅须知" width="120" />
        <el-table-column prop="subscriptionNotice"    label="订阅须知" width="120" />
        <el-table-column prop="collects"              label="收藏量" width="120" />
        <el-table-column prop="pjCount"               label="评价数量" width="120" />
        <el-table-column prop="originalPrice"         label="原始价格" width="120" />
        <el-table-column prop="discountPrice"         label="折扣价格" width="120" />
        <el-table-column prop="learningTimes"         label="学习次数" width="120" />
        <el-table-column prop="termOfValidity"        label="有效期" width="120" />
        <el-table-column prop="namea"                 label="扩展1" width="120" />
        <el-table-column prop="nameb"                 label="扩展2" width="120" />
        <el-table-column fixed="right"                label="操作" min-width="120">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="toEdit(scope.row)">修改</el-button>
            <el-button link type="primary" @click="onDel(scope.row.id)" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-scrollbar>
  </div>

  <el-pagination style="margin-top: 10px;"
                 v-model:current-page="queryInfo.pageNum"
                 v-model:page-size="queryInfo.pageSize"
                 :page-sizes="[1, 5, 10]"
                 size="default"
                 background="false"
                 layout="total, sizes, prev, pager, next, jumper"
                 :total="totalNum"
                 @size-change="handleSizeChange"
                 @current-change="handleCurrentChange"
  />



  <!-- 添加，编辑弹框 -->
  <el-dialog v-model="saveOrUpdateVisible" :title="saveOrUpdateTitle" width="700">
    <el-form :model="article">
      <el-form-item label="课程名" :label-width="formLabelWidth">
        <el-input v-model="article.courseName" autocomplete="off" />
      </el-form-item>
      <el-form-item label="简介" :label-width="formLabelWidth">
        <el-input v-model="article.courseIntroduce" autocomplete="off" type="textarea" :rows="4"/>
      </el-form-item>
      <el-form-item label="适用人群" :label-width="formLabelWidth">
        <el-input v-model="article.applicablePopulation" autocomplete="off" />
      </el-form-item>
      <el-form-item label="分类" :label-width="formLabelWidth">
        <el-cascader  :options="courseTypeArraylist" clearable
                      :props="{value:'courseTypeId',label:'courseTypeName'}"
                      v-model="aaa"
                      @change="handleAreaIdChange" />
      </el-form-item>
      <el-form-item label="学习收获" :label-width="formLabelWidth">
        <el-input v-model="article.learnHarvest" autocomplete="off" />
      </el-form-item>
      <el-form-item label="订阅须知" :label-width="formLabelWidth">
        <el-input v-model="article.subscriptionNotice" autocomplete="off" />
      </el-form-item>
      <el-form-item label="原始价格" :label-width="formLabelWidth">
        <el-input v-model="article.originalPrice" autocomplete="off" />
      </el-form-item>
      <el-form-item label="扩展1" :label-width="formLabelWidth">
        <el-input v-model="article.namea" autocomplete="off" />
      </el-form-item>
      <el-form-item label="扩展2" :label-width="formLabelWidth">
        <el-input v-model="article.nameb" autocomplete="off" />
      </el-form-item>
      <el-form-item label="图片" :label-width="formLabelWidth">
        <el-upload
            v-model:file-list="fileList"
            class="avatar-uploader"
            list-type="picture-card"
            action="http://localhost/file/upload"
            :on-success="handleAvatarSuccess"
        >
          <img v-if="!fileList" :src="imageUrl" class="avatar"  alt=""/>
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="视频" :label-width="formLabelWidth">
        <el-upload
            class="avatar-uploader"
            list-type="picture-card"
            action="http://localhost/file/upload"
            :on-success="handleAvatar"
        ></el-upload>
      </el-form-item>


    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="saveOrUpdate">
          {{saveOrUpdateTitle }}
        </el-button>
      </div>
    </template>
  </el-dialog>

</template>
<script setup>
import {onMounted, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios';
import {Plus} from "@element-plus/icons-vue";
import router from '@/router';

let aaa=ref(1);
//获取咨询师登录信息
let zxsxxi=ref( "")
let a = {
  name: JSON.parse(sessionStorage.getItem('loginInfor')).name
}
let b = {//如果是管理员，可以看所有课程，是咨询师可以看自己的课程，是客服可以看啥也不准看
  role: JSON.parse(sessionStorage.getItem('loginInfor')).role
}

const c=()=>{zxsxxi.value=JSON.parse(sessionStorage.getItem('loginInfor'))}
c();
let id=ref(0);//咨询师id
//console.log('zxsxxi',zxsxxi.value);
const zxs=()=>{
  console.log(a.name);
  
  axios.get("/consult/findConsultByName",{params:{name:a.name}})
      .then(res=>{
        console.log(res);
        
        id.value=res.data.data.id;
        console.log(id.value);
        getList(id.value)
      })
}
onMounted(()=>{
  getAllList(); 
})

const getAllList = () => {
  //console.log(b.role);
  
  if(b.role==1){
   axios.get("/course/findAll",{
    params:{
      pageNum:queryInfo.value.pageNum,
      pageSize:queryInfo.value.pageSize
    }
  }) 
   .then(res=>{
      console.log(1111,res)
      kcArray.value=res.data.data.list;
      console.log(kcArray.value);
      //console.log(kcArray.value);
      totalNum.value=res.data.data.total;
      //console.log("课程",kcArray.value)
   })
  }else if(b.role==2){
    zxs();
  }else if(b.role==3){
    ElMessageBox.alert('您没有权限查看', '提示', {
      confirmButtonText: '确定',
      callback: action => {
        router.push('/homepage');
      },
    });
  }
}

const getList = (id) => {
  //console.log(id)
  axios.put("/course/findcoursebyid?id="+id+"&pageNum="+queryInfo.value.pageNum+"&pageSize="+queryInfo.value.pageSize)
    .then(res=>{
      //console.log(res)
      kcArray.value=res.data.data.list;
      //console.log(kcArray.value);
      total.value=res.data.data.total;
      //console.log("课程",kcArray.value)
    })
} 

let kcArray=ref([]);

const fileList = ref([]);
const imageUrl=ref('');
// 定义一个数据总条数
const totalNum = ref(0);
// 图片上传
const handleAvatarSuccess = (response, uploadFile)  => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw);
  console.log("图片名称",URL.createObjectURL(uploadFile.raw))
  // 一旦上传成功，则需要把返回的数据赋值给article.imageUrl
  article.value.tabularChart = response.data;
}
//视频上传
const handleAvatar = (response,uploadFile)  => {
  article.value.courseVideo = response.data;
}

// 修改或添加
const saveOrUpdateVisible = ref(false);
const article = ref({
  courseName:'',
  courseTime:'',
  courseMount:1,
  tabularChart:'',
  courseIntroduce:'',
  applicablePopulation:'',
  typeId:0,
  teacherId:0,
  teacherName:'',
  learnHarvest:'',
  subscriptionNotice:'',
  collects:'',
  courseVideo:'',
  pjCount:0,
  originalPrice:0,
  discountPrice:0,
  learningTimes:0,
  termOfValidity:'无限',
  namea:'',
  nameb:'',
})
const saveOrUpdateTitle = ref('添加');
// 去修改的页面
const toEdit = row=>{
  saveOrUpdateVisible.value = true;
  isEdit.value = false;
  saveOrUpdateTitle.value = '编辑';
  article.value = row;
  aaa.value=article.value.typeId;
  // 把图片的名称和路径放入到fileList中
  fileList.value = [{
    name: '0000',
    url: url.value + article.value.tabularChart
  }];
}
//添加true 修改false
let isEdit=ref(false);
// 去添加的页面
const toAdd = row=>{
  saveOrUpdateVisible.value = true;
  saveOrUpdateTitle.value = '添加';
  isEdit.value = true;
  article.value = {
    courseName:'',
    courseTime:'',
    courseMount:1,
    tabularChart:'',
    courseIntroduce:'',
    applicablePopulation:'',
    typeId:0,
    teacherId:0,
    learnHarvest:'',
    subscriptionNotice:'',
    collects:'',
    courseVideo:'',
    pjCount:0,
    originalPrice:0,
    discountPrice:0,
    learningTimes:0,
    termOfValidity:'无限',
    namea:'',
    nameb:'',
  };
  article.value.teacherId=id.value;

}

// 取消修改或保存
const close = ()=>{
  saveOrUpdateVisible.value = false;
  // 请求图片展示
  imageUrl.value = '';
  fileList.value = [];

}
const handleAreaIdChange =(selectedAreaIds)=> {
  const finalAreaId = selectedAreaIds[selectedAreaIds.length - 1];
  console.log('最终的areaId为：', finalAreaId);
  article.value.typeId=finalAreaId;
  // 在这里可以进行后续的业务逻辑，比如赋值给其他变量、传递给后端等
  aaa.value=finalAreaId;
  areaId.value=aaa.value;

}
let areaId=ref(0);
// 保存或更新
const saveOrUpdate = ()=>{
  if(saveOrUpdateTitle.value == '添加'){
    // 调用后端接口添加
    axios.put('/course/addcourse',article.value)
        .then(resp=>{
          // console.log(resp.data)
          let result =  resp.data;  // resp是promise对象，.data返回我们自己的标准R
          getAllList();
        })
  } else{
    // 调用后端接口修改
    axios.put('/course/updatecourse',article.value)
        .then(resp=>{
          let result =  resp.data;  // resp是promise对象，.data返回我们自己的标准R
          if(result.code==1){
            // 重新获取列表
            getAllList();
          } else{
            console.log('修改文章失败')
          }
        })
  }
  // 关闭弹框
  saveOrUpdateVisible.value = false;
  // 请求图片展示
  imageUrl.value = '';
}



// 定义一个路径
const url = ref("http://localhost/file/downLoad?fileName=");

// 定义一个全局的查询参数变量
const queryInfo = ref({
  pageNum:1,
  pageSize:5,
  name:''
})
const coursetypeArray= ()=>{
  axios.get("/coursetype/findAllCoursetype")
  .then(res=>{
    courseTypeArraylist.value=res.data.data
    console.log("课程类型",courseTypeArraylist.value)
  })
};
coursetypeArray();
//课程类型
let courseTypeArraylist=ref([]);
// 分页
const handleSizeChange = (val) => {
  queryInfo.value.pageSize = val;
  queryInfo.value.pageNum = 1;
  getAllList();

}
const handleCurrentChange = (val) => {
  queryInfo.value.pageNum = val;
  getAllList();
}


// 删除
const onDel = id=>{
  ElMessageBox.confirm(
      '真的要删除吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        // 调用后端接口删除
        axios.put('/course/deletecourse?id='+id)
            .then(resp=>{
              // console.log(resp.data)
              let result =  resp.data;  // resp是promise对象，.data返回我们自己的标准R
              if(result.code==1){
                // 重新获取列表
                getAllList();
                ElMessage({
                  message: '删除成功！',
                  type: 'success',
                })
              }else{
                ElMessage({
                  message: '删除失败！',
                  type: 'warning',
                })
              }
            })


      })
      .catch(() => {})
}
</script>




<style scoped>

</style>
